package com.zjr.friend.service.user.imp;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjr.common.core.constants.Constants;
import com.zjr.common.core.domain.R;
import com.zjr.common.core.domain.TableDataInfo;
import com.zjr.common.core.enums.ExamListType;
import com.zjr.common.core.enums.ResultCode;
import com.zjr.common.core.utils.ThreadLocalUtil;
import com.zjr.common.redis.service.RedisService;
import com.zjr.common.security.exception.ServiceException;
import com.zjr.common.security.service.TokenService;
import com.zjr.friend.domain.exam.Exam;
import com.zjr.friend.domain.exam.dto.ExamDTO;
import com.zjr.friend.domain.exam.dto.ExamQueryDTO;
import com.zjr.friend.domain.exam.vo.ExamVO;
import com.zjr.friend.domain.user.UserExam;
import com.zjr.friend.manager.ExamCacheManager;
import com.zjr.friend.mapper.exam.ExamMapper;
import com.zjr.friend.mapper.user.UserExamMapper;
import com.zjr.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImp implements IUserExamService {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    ExamCacheManager examCacheManager;
    @Override
    public int enter(String token, ExamDTO examDTO) {
        Exam exam = examMapper.selectById(examDTO.getExamId());
        // 竞赛是否存在
        if(exam == null){
            throw new ServiceException(ResultCode.EXAM_NOT_EXITS);
        }
        // 竞赛是否已经开始
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_START);
        }
//        Long userId = tokenService.getUserId(token, secret);
        // 通过 ThreadLocal 快速获取 userId
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        // 查询该用户是否已经报名
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examDTO.getExamId())
                .eq(UserExam::getUserId, userId));
        if(userExam != null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        // 将数据放入 redis 中 - (user:exam:list:{userId}, [].add(examId))
        examCacheManager.addUserExamCache(userId, examDTO.getExamId());

        // 将数据放入 mysql 中
        userExam = new UserExam();
        userExam.setExamId(examDTO.getExamId());
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        // 通过 ThreadLocal 快速获取 userId
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);

        // 从 redis 中获取 user:exam:userId 对应的 list 的大小
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);

        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            // 分页
            // 从数据库 中读取数据 并将数据存储到 redis 中
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), null);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
//        assembleExamVOList(examVOList);
        return TableDataInfo.success(examVOList, total);
    }
}
